package com.xinfu.newproject.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.xinfu.newproject.R;
import com.xinfu.newproject.adapter.certification.ResidentCertificationAdapter;
import com.xinfu.newproject.base.BaseActivity;
import com.xinfu.newproject.bean.certifition.ResidentBean;
import com.xinfu.newproject.bean.certifition.ResidentCertificationBean;
import com.xinfu.newproject.bean.login.LoginBean;
import com.xinfu.newproject.contants.Contants;
import com.xinfu.newproject.ui.pay_cost.PayCostTypeActivity;
import com.xinfu.newproject.ui.resident_certifition.BackHandledInterface;
import com.xinfu.newproject.ui.resident_certifition.CertifitionAuditFragment;
import com.xinfu.newproject.ui.resident_certifition.MyCertifitionFragment;
import com.xinfu.newproject.presenter.QueryPropertyPresenter;
import com.xinfu.newproject.util.AlertDialog;
import com.xinfu.newproject.util.BToast;
import com.xinfu.newproject.util.SPUtils;
import com.xinfu.newproject.view.IView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

import static com.xinfu.newproject.contants.Constant.LOGIN;

public class ResidentCertificationActivity extends BaseActivity implements BackHandledInterface, IView.IQueryPropertyView, FragmentManager.OnBackStackChangedListener {

    private AlertDialog alertDialog;

    @BindView(R.id.activity_resident_certification_rv)
    RecyclerView mRecyclerView;

    @BindView(R.id.activity_resident_certification_fl)
    FrameLayout frameLayout;

    @BindView(R.id.layout_next_step_tv)
    TextView nextTv;

    private FragmentManager fragmentManager;
    public final static int FRAGMENT_ZERO = 0;
    public final static int FRAGMENT_ONE = 1;
    public final static int FRAGMENT_TWO = 2;

    private MyCertifitionFragment myCertifitionFragment;
    private CertifitionAuditFragment certifitionAuditFragment;

    private ResidentCertificationAdapter residentCertificationAdapter;

    private QueryPropertyPresenter queryPropertyPresenter = new QueryPropertyPresenter(this);
    private Disposable mDisposable;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_resident_certification);
        ButterKnife.bind(this);
        registerBack();
        initViewBind();
        initLisener();
    }

    private void initLisener() {
        if (isAddRoom() == 1) {
            queryPropertyPresenter.queryProperty();//请求绑定的房间
        }

        alertDialog.setGone().setTitle("您还未通过住户认证？ 认证成功即可尊享专属物业服务").setMsg("简单2步，开启您的专属服务").setCancelable(false).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        }).setPositiveButton("立即认证", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFragment(FRAGMENT_ONE, null);
            }
        });
    }

    private void initViewBind() {
        if (getIntent().getExtras().getInt("type", -1) == Contants.CHOOSECOMMUNITYCERTIFITION) {
            setActivityTitle("请选择户号");
            nextTv.setVisibility(View.GONE);
        } else if (getIntent().getExtras().getInt("type", -1) == Contants.PAYCOSTCHOOSECOMMUNITYCERTIFITION) {
            setActivityTitle("请选择房间");
            nextTv.setVisibility(View.GONE);
        } else {
            setActivityTitle("住户认证");
            nextTv.setText("添加认证房间");
            nextTv.setVisibility(View.VISIBLE);
        }

        alertDialog = new AlertDialog(this).builder();
        fragmentManager = getSupportFragmentManager();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        residentCertificationAdapter = new ResidentCertificationAdapter(R.layout.item_resident_certification_content, R.layout.item_resident_certification, residentBean);

        residentCertificationAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (getIntent().getIntExtra("type", -1) == Contants.CHOOSECOMMUNITYCERTIFITION) {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString("community", new Gson().toJson(residentBean.get(position)));
                    bundle.putString("partType", getIntent().getExtras().getString("partType"));
                    ResidentCertificationBean.ResultBean.RoomCheckUserListBean video = (ResidentCertificationBean.ResultBean.RoomCheckUserListBean) residentBean.get(position).t;
                    for (int i = 0; i < certificationBean.getResult().size(); i++) {
                        if (video.getProjectId().equals(certificationBean.getResult().get(i).getId())) {
                            bundle.putString("title", certificationBean.getResult().get(i).getName());
                        }
                    }
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    finish();
                } else if (getIntent().getIntExtra("type", -1) == Contants.PAYCOSTCHOOSECOMMUNITYCERTIFITION) {
                    ResidentCertificationBean.ResultBean.RoomCheckUserListBean video = (ResidentCertificationBean.ResultBean.RoomCheckUserListBean) residentBean.get(position).t;
                    if (video.getAuditRes() == 1) {
                        Bundle bundle = new Bundle();
                        bundle.putString("response", new Gson().toJson(residentBean.get(position)));
                        startIntentActivity(PayCostTypeActivity.class, bundle);
                    } else {
                        BToast.showText(ResidentCertificationActivity.this, "请选择已认证房产");
                    }
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("response", new Gson().toJson(residentBean.get(position)));
                    showFragment(FRAGMENT_TWO, bundle);
                }
            }
        });
//        residentCertificationAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//
//            }
//        });
        mRecyclerView.setAdapter(residentCertificationAdapter);
    }

    public void showFragment(int index, Bundle bundle) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        hideFragments(ft);
        //注意这里设置位置
//        position = index;
        switch (index) {
            case FRAGMENT_ZERO:
                fragmentManager.popBackStack();
                if (isAddRoom() == 1) {
                    queryPropertyPresenter.queryProperty();//请求绑定的房间
                }
                break;
            case FRAGMENT_ONE:
                /**
                 * 如果Fragment为空，就新建一个实例
                 * 如果不为空，就将它从栈中显示出来
                 */
                frameLayout.setVisibility(View.VISIBLE);
                myCertifitionFragment = MyCertifitionFragment.newInstance();
                fragment = myCertifitionFragment;
                ft.add(R.id.activity_resident_certification_fl, myCertifitionFragment);
                ft.addToBackStack(null);
                break;
            case FRAGMENT_TWO:
                certifitionAuditFragment = new CertifitionAuditFragment();
                fragment = certifitionAuditFragment;
                certifitionAuditFragment.setArguments(bundle);
                ft.add(R.id.activity_resident_certification_fl, certifitionAuditFragment);
                ft.addToBackStack(null);
                break;
        }
        ft.commitAllowingStateLoss();
    }

    @Override
    public void setSelectedFragment(int selectedFragment) {
        showFragment(selectedFragment, null);
    }

    /**
     * 隐藏fragment
     *
     * @param transaction
     */
    private void hideFragments(FragmentTransaction transaction) {

        if (myCertifitionFragment != null) {
            transaction.hide(myCertifitionFragment);
        }
        if (certifitionAuditFragment != null) {
            transaction.hide(certifitionAuditFragment);
        }
    }

    @OnClick({R.id.layout_next_step_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_next_step_tv:
                showFragment(FRAGMENT_ONE, null);
                break;
        }
    }

    //解决重叠，方法1
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //如果用以下这种做法则不保存状态，再次进来的话会显示默认的tab
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Log.i("testResident", "111111");
        if (fragmentManager.getBackStackEntryCount() < 0) {
            finish();
        } else {
            showFragment(FRAGMENT_ZERO, null);
            if (isAddRoom() == 1) {
                queryPropertyPresenter.queryProperty();//请求绑定的房间
            }
        }
    }

    /**
     * 判断是否可以请求数据
     *
     * @return
     */
    String token, userId, auditRes;

    private Integer isAddRoom() {
        LoginBean.ResultBean resultBean;
        String responseIntent = (String) SPUtils.get(this, LOGIN, "0");
        if (!responseIntent.equals("0")) {
            resultBean = new Gson().fromJson(responseIntent, LoginBean.ResultBean.class);
            token = resultBean.getToken();
            userId = resultBean.getUserInfo().getId();
        } else {
            BToast.showText(this, "请先登录");
            return 0;
        }
        if (getIntent().getIntExtra("type", -1) == Contants.CHOOSECOMMUNITYCERTIFITION) {
            auditRes = "1";
        } else {
            auditRes = "0";
        }
        if (responseIntent == null) {

            return 0;
        }

        return 1;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    @Override
    public String header() {
        return token;
    }

    @Override
    public String userId() {
        return userId;
    }

    @Override
    public String auditRes() {
        return auditRes;
    }

    @Override
    public void showToast(String content) {
//        BToast.showText(this, content);
    }

    @Override
    public void closeDispose(Disposable disposable) {
        this.mDisposable = disposable;
    }

    List<ResidentBean> residentBean = new ArrayList<>();
    ResidentCertificationBean certificationBean;
    @Override
    public void getData(ResidentCertificationBean residentCertificationBean) {
        residentBean.clear();
        certificationBean = residentCertificationBean;
        residentBean = getSampleData(residentCertificationBean);
        residentCertificationAdapter.setNewData(residentBean);
        if (residentCertificationBean.getResult().size() > 0) {
            if (alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            frameLayout.setVisibility(View.VISIBLE);
        } else {
            alertDialog.show();
            frameLayout.setVisibility(View.GONE);
        }
    }

    public static List<ResidentBean> getSampleData(ResidentCertificationBean residentCertificationBean) {
        List<ResidentBean> list = new ArrayList<>();
        for (int i = 0; i < residentCertificationBean.getResult().size(); i++) {
            ResidentBean residentBean = new ResidentBean(true, residentCertificationBean.getResult().get(i).getName(), true);
            list.add(residentBean);
            for (int j = 0; j < residentCertificationBean.getResult().get(i).getRoomCheckUserList().size(); j++) {
                ResidentCertificationBean.ResultBean.RoomCheckUserListBean roomCheckUserListBean = new ResidentCertificationBean.ResultBean.RoomCheckUserListBean(
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getId(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getUserId(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getUserName(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getRoomId(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getApplyName(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getApplyTel(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getApplyCusName(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getApplyCusTel(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getAddress(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getIdType(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getAuditRes(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getAuditBy(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getAuditComment(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getAuditDate(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getImgUrl(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getRemarks(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getDelFlag(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getProjectId(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getProjectName(),
                        residentCertificationBean.getResult().get(i).getRoomCheckUserList().get(j).getTenantId());
                list.add(new ResidentBean(roomCheckUserListBean));
            }

        }

        return list;
    }


    @Override
    public void onBackStackChanged() {

    }

    Fragment fragment;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

//        if (fragment instanceof MyCertifitionFragment) {
//            MyCertifitionFragment.onKeyDown(keyCode, event);
//            showFragment(FRAGMENT_ZERO,null);
//        }
        return super.onKeyDown(keyCode, event);
    }
}
